import ConfirmModal from "@/components/ConfirmModal";
import { useDeviceMode } from "@/hooks/useDeviceMode";
import { PrismaClient } from "@prisma/client";
import { Modal } from "antd";
import Cookies from "cookies";
import Head from "next/head";
import { useRouter } from "next/router";
import { useRef } from "react";

interface ArticleDetailProps {
  content: string;
  id: string;
  title: string;
  user: { name: string };
  tags: { name: string; color: string; background: string }[];
  createdAt: string;
  views: number;
}

function formatTime(timestamp: number): string {
  const now = Date.now();
  const diff = now - timestamp;

  const seconds = Math.floor(diff / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  if (days > 3) {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${(date.getMonth() + 1)
      .toString()
      .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${date
      .getHours()
      .toString()
      .padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`;
  } else if (days === 3) {
    return "三天前";
  } else if (days === 2) {
    return "昨天";
  } else if (days === 1) {
    return "今天";
  } else if (hours < 1) {
    return "刚刚";
  } else {
    return `${hours} 小时前`;
  }
}
const ArticleDetailPage = (props: {
  detail: ArticleDetailProps;
  editable: boolean;
  deleteable: boolean;
}) => {
  const mobile = useDeviceMode();
  const pcStyles = {
    boxSizing: "border-box",
    width: "1000px",
    margin: "0 auto",
  } as any;
  const mobileStyles = {
    boxSizing: "border-box",
    width: "100vw",
    margin: "0 auto",
  } as any;

  const router = useRouter();
  function handleEdit() {
    router.push("/write?id=" + props.detail.id);
  }
  // Pc端的
  const [modal, ctxh] = Modal.useModal();

  // 移动端的
  const modalRef = useRef<{ close: () => void; open: () => void } | null>(null);
  const handleMobileDelete = async (close: () => void) => {
    await fetch("/api/delete-article?id=" + props.detail.id, {
      method: "GET",
    });
    router.back();
    close();
  };
  async function handleDelete() {
    if (mobile) {
      modalRef.current?.open();
    } else {
      const confirmed = await modal.confirm({
        title: props.detail.title,
        content: "确认删除吗",
        type: "warning",
      });
      if (confirmed) {
        await fetch("/api/delete-article?id=" + props.detail.id, {
          method: "GET",
        });
        router.back();
      }
    }
  }

  return (
    <>
      <ConfirmModal
        type="warning"
        ref={modalRef}
        onConfirm={handleMobileDelete}
      />
      {ctxh}
      <Head>
        <title>
          {props.detail.title} | {props.detail.user.name}
        </title>
        <meta
          name="keywords"
          content={props.detail.title + "," + props.detail.user.name}
        ></meta>
      </Head>
      <div style={mobile ? mobileStyles : pcStyles} id="article-detail-root">
        <h1
          className={
            mobile
              ? "text-3xl text-center pt-8 mb-8"
              : "text-4xl text-center pt-8 mb-8"
          }
        >
          {props.detail.title}
        </h1>
        <div className="text-center mb-8">
          <span className="text-xm" style={{ color: "#999" }}>
            {formatTime(Date.parse(props.detail.createdAt))}
            <span style={{ color: "#49e" }}>@</span>
            {props.detail.user.name}
          </span>

          <span>
            &#x3000;
            {props.detail.tags.map((tag) => (
              <span
                className="mr-1"
                style={{
                  color: tag.color,
                  background: tag.background,
                  padding: "2px 6px",
                  borderRadius: "20px",
                  fontSize: mobile ? "12px" : "14px",
                }}
              >
                {tag.name}
              </span>
            ))}
          </span>
        </div>
        <div
          style={{
            fontSize: mobile ? "14px" : "auto",
            padding: mobile ? "0 4vw" : "0",
            color: mobile ? "#494949" : "auto",
          }}
          dangerouslySetInnerHTML={{ __html: props.detail.content }}
        ></div>

        <div
          style={{
            padding: mobile ? "4px 4vw" : "4px  0",
            borderTop: "1px dashed #f1f1f1",
          }}
        >
          <span>Views👀:{props.detail.views}</span>
          {props.editable && (
            <span onClick={handleEdit} className="ml-2 cursor-pointer">
              |&nbsp;🛠️编辑
            </span>
          )}
          {props.deleteable && (
            <span onClick={handleDelete} className="ml-2 cursor-pointer">
              |&nbsp;🆘删除
            </span>
          )}
        </div>
      </div>
    </>
  );
};

export default ArticleDetailPage;

export async function getServerSideProps(context: {
  req: any;
  res: any;
  params: { id: string };
}) {
  const prisma = new PrismaClient();
  await prisma.article.update({
    where: {
      id: context.params.id,
    },
    data: {
      views: {
        increment: 1,
      },
    },
  });
  const detail = await prisma.article.findUnique({
    where: { id: context.params.id },
    select: {
      id: true,
      title: true,
      content: true,
      createdAt: true,
      views: true,
      user: {
        select: {
          name: true,
          id: true,
        },
      },
      tags: {
        select: {
          name: true,
          color: true,
          background: true,
        },
      },
    },
  });

  const cookier = new Cookies(context.req, context.res);

  const userEncoded = decodeURIComponent(
    decodeURIComponent(cookier.get("user") as string),
  );

  if (!userEncoded) {
    return {
      props: {
        detail: detail ? JSON.parse(JSON.stringify(detail)) : {},
        editable: false,
        deleteable: false,
      },
    };
  }

  let user = JSON.parse(userEncoded);
  return {
    props: {
      detail: detail ? JSON.parse(JSON.stringify(detail)) : {},
      editable: detail?.user.id === user.id,
      deleteable: detail?.user.id === user.id,
    },
  };
}
